package com.admin.control;

import com.grid.entity.*;
import com.admin.entity.TableData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;


public class AQIdistributetotalstatisViewControl {
    @FXML
    private TableView<TableData> tableView;
    private static final String AQI_FILE = "AQI.txt";
    private List<AQI> aqilist = new ArrayList<>();
    private int count1 = 0;
    private int count2 = 0;
    private int count3 = 0;
    private int count4 = 0;
    private int count5 = 0;
    private int count6 = 0;

    @FXML
    private void initialize() {
        try {
            aqilist = loadAQIData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (AQI aqi : aqilist) {
            if (aqi.getAQI() > 0 && aqi.getAQI() <= 50){
                count1++;
            }else if (aqi.getAQI() > 50 && aqi.getAQI() <= 100){
                count2++;
            }else if(aqi.getAQI() > 100 && aqi.getAQI() <= 150){
                count3++;
            }else if(aqi.getAQI() > 150 && aqi.getAQI() <= 200){
                count4++;
            }else if(aqi.getAQI() > 200 && aqi.getAQI() <= 300){
                count5++;
            }else{
                count6++;
            }
        }

        ObservableList<TableData> data = FXCollections.observableArrayList(
                new TableData("1", "良", String.valueOf(count1)),
                new TableData("2", "良", String.valueOf(count2)),
                new TableData("3", "轻度污染", String.valueOf(count3)),
                new TableData("4", "中度污染", String.valueOf(count4)),
                new TableData("5", "重度污染",String.valueOf(count5)),
                new TableData("6", "严重污染", String.valueOf(count6)));
        tableView.setItems(data);
    }

    private List<AQI> loadAQIData() throws IOException {
        File file = new File(AQI_FILE);
        if (!file.exists() || file.length() == 0) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<AQI>) ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException("数据文件格式错误", e);
        }
    }
}
